package com.skill.shareskill.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.skill.shareskill.R;
import com.skill.shareskill.activity.DetailActivityActivity;
import com.skill.shareskill.activity.SearchActivityActivity;
import com.skill.shareskill.adapter.MainActivityGroupAdapter;
import com.skill.shareskill.adapter.MainIntelligentAdapter;
import com.skill.shareskill.adapter.MainLocalAdapter;
import com.skill.shareskill.adapter.MainSuperAdapter;
import com.skill.shareskill.bean.ActivityGroup;
import com.skill.shareskill.bean.ActivityItem;
import com.skill.shareskill.bean.User;
import com.skill.shareskill.service.LoadDataThread;
import com.skill.shareskill.utils.HorizontalListView;
import com.skill.shareskill.utils.HttpUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/1/31 0031.
 */

public class MainFragment extends Fragment {
    private ViewPager vp_main_super;
    private HorizontalListView hv_main_super; //重磅推荐
    private HorizontalListView hv_main_local;   //本地推荐
    private HorizontalListView hv_main_intelligent; //达人推荐
    private HorizontalListView hv_main_activity_group;  //活动圈
    private Gson gson=new Gson();
    private MainLocalAdapter mainLocalAdapter;
    private MainSuperAdapter mainSuperAdapter;
    private MainIntelligentAdapter mainIntelligentAdapter;
    private List<ActivityItem> activityItemList;
    private List<User> userList;

    private List<ImageView> imgs = new ArrayList<ImageView>();
    private LinearLayout ll_main_super_points; //增加小点图标
    private TextView tv_main_super_title; //设置标题
    private List<ImageView> points = new ArrayList<ImageView>(); //存放小图标集合
    private String[] titles = { "娱乐新闻", "国内新闻", "国际新闻", "体育新闻" };

    private TextView tv_main_search;

    private Handler handler=new Handler(){
        public void handleMessage(Message message){
            String activityJson= (String) message.obj;
            Log.d("network", "sb==>" + activityJson);
           // activityBean=gson.fromJson(activityJson,ActivityBean.class);
            userList=gson.fromJson(activityJson, new TypeToken<List<User>>(){}.getType());
            if(mainIntelligentAdapter==null){
                //activityAdapter=new ActivityItemAdapter(getActivity(),activityBean.getActivity());
                mainIntelligentAdapter=new MainIntelligentAdapter(getActivity(),userList);
                hv_main_intelligent.setAdapter(mainIntelligentAdapter);
            }else{
                mainIntelligentAdapter.notifyDataSetChanged();
            }
        }

    };
    private Handler localHandle=new Handler(){
        public void handleMessage(Message message){
            String activityJson= (String) message.obj;
            activityItemList=gson.fromJson(activityJson, new TypeToken<List<ActivityItem>>(){}.getType());
            if(mainLocalAdapter==null){
                mainLocalAdapter=new MainLocalAdapter(getActivity(),activityItemList);
                hv_main_local.setAdapter(mainLocalAdapter);
            }else{
                mainLocalAdapter.notifyDataSetChanged();
            }
        }
    };
    private Handler superHandle=new Handler(){
        public void handleMessage(Message message){
            String activityJson= (String) message.obj;
            activityItemList=gson.fromJson(activityJson, new TypeToken<List<ActivityItem>>(){}.getType());
            if(mainSuperAdapter==null){
                mainSuperAdapter=new MainSuperAdapter(getActivity(),activityItemList);
                hv_main_super.setAdapter(mainSuperAdapter);
            }else{
                mainSuperAdapter.notifyDataSetChanged();
            }
        }
    };
    private Handler activityGroupHandle=new Handler(){
        public void handleMessage(Message message){
            String activityJson= (String) message.obj;
            activityItemList=gson.fromJson(activityJson, new TypeToken<List<ActivityItem>>(){}.getType());
            if(mainSuperAdapter==null){
                mainSuperAdapter=new MainSuperAdapter(getActivity(),activityItemList);
                hv_main_super.setAdapter(mainSuperAdapter);
            }else{
                mainSuperAdapter.notifyDataSetChanged();
            }
        }
    };

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //控制搜索框图标大小
        tv_main_search= view.findViewById(R.id.tv_main_search);
        Drawable drawable1 = getResources().getDrawable(R.drawable.icon_main_search);
        drawable1.setBounds(10, 0, 60, 60);//第一0是距左边距离，第二0是距上边距离，60分别是长宽
        tv_main_search.setCompoundDrawables(drawable1, null, null, null);//只放左边
        tv_main_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(getActivity(),SearchActivityActivity.class);
                startActivity(intent);
            }
        });

        vp_main_super=view.findViewById(R.id.vp_main_super);

        ll_main_super_points=view.findViewById(R.id.ll_main_super_points);
        tv_main_super_title=view.findViewById(R.id.tv_main_super_title);
        initDatas();
        vp_main_super.setAdapter(new MyPagerAdapter());

        //给viewPager增加滑动监听事件
        vp_main_super.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            //当viewPager中某个界面被选中时调用
            @Override
            public void onPageSelected(int position) {
                changePoint(position);
            }



            //viewPager在滑动时被调用
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                // TODO Auto-generated method stub

            }

            //viewPager滑动状态改动时被调用
            @Override
            public void onPageScrollStateChanged(int state) {
                // TODO Auto-generated method stub

            }
        });

        //初始化标题
        tv_main_super_title.setText(titles[0]);

        //初始化小图标
        for (int i = 0; i < imgs.size(); i++) {
            ImageView iv_point = new ImageView(this.getActivity());
            if (i == 0) {
                iv_point.setImageResource(R.drawable.page_control_on);
            } else {
                iv_point.setImageResource(R.drawable.page_control_off);
            }
            //给小点图标设置间隔
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            params.setMargins(5, 0, 5, 0);
            iv_point.setLayoutParams(params);


            iv_point.setId(i);
           //iv_point.setOnClickListener();

            points.add(iv_point);
            ll_main_super_points.addView(iv_point);
        }
        hv_main_super=getActivity().findViewById(R.id.hv_main_super);
        hv_main_local=getActivity().findViewById(R.id.hv_main_local);
        hv_main_intelligent=getActivity().findViewById(R.id.hv_main_intelligent);
        hv_main_activity_group=getActivity().findViewById(R.id.hv_main_activity_group);
        //添加ListView点击事件
        hv_main_local.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String actNo=((String)((TextView) view.findViewById(R.id.tv_local_actNo)).getText()).trim();
                Toast.makeText(getActivity(),actNo,Toast.LENGTH_LONG).show();
                Intent intent=new Intent(getActivity(), DetailActivityActivity.class);
                intent.putExtra("actNo",actNo);
                startActivity(intent);
            }
        });
        String superUrl=HttpUtils.BASE_PATH+"activity/queryAllActivity";
        LoadDataThread superLAT=new LoadDataThread(superHandle,superUrl);
        superLAT.start();

        String localActivityUrl=HttpUtils.BASE_PATH+"activity/queryAllActivity";
        LoadDataThread localLAT=new LoadDataThread(localHandle,localActivityUrl);
        localLAT.start();

        String intelligentUrl=HttpUtils.BASE_PATH+"user/queryAllUser";
        LoadDataThread intelligentLAT=new LoadDataThread(handler,intelligentUrl);
        intelligentLAT.start();

//        String activityGroupUrl="";
//        LoadDataThread activityGroupLAT=new LoadDataThread(activityGroupHandle,activityGroupUrl);
//        activityGroupLAT.start();
        ActivityGroup activityGroup=new ActivityGroup("imgs/EZ.jpg","上海");
        ActivityGroup activityGroup1=new ActivityGroup("imgs/EZ.jpg","上海");
        ActivityGroup activityGroup2=new ActivityGroup("imgs/EZ.jpg","上海");
        ActivityGroup activityGroup3=new ActivityGroup("imgs/EZ.jpg","上海");
        ActivityGroup activityGroup4=new ActivityGroup("imgs/EZ.jpg","上海");

        List<ActivityGroup> list=new ArrayList<ActivityGroup>();
        list.add(activityGroup);
        list.add(activityGroup1);
        list.add(activityGroup2);
        list.add(activityGroup3);
        list.add(activityGroup4);

        hv_main_activity_group.setAdapter(new MainActivityGroupAdapter(getContext(),list));



    }

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
        /**
         * View inflate(int resource, ViewGroup root, boolean attachToRoot)
         * 参数：
         * resource：指的是要加载的布局文件
         * container：
         * attachToRoot：是否要加fragmnet加到根布局
         */
        View view=inflater.inflate(R.layout.fragment_main,container,false);


        return view;
    }
    //初始化数据
    private void initDatas() {
        // TODO Auto-generated method stub
        ImageView iv1 = new ImageView(this.getActivity());
        //		iv1.setImageResource(R.drawable.pic1);
        iv1.setBackgroundResource(R.drawable.pic1);

        ImageView iv2 = new ImageView(this.getActivity());
        //		iv2.setImageResource(R.drawable.pic2);
        iv2.setBackgroundResource(R.drawable.pic2);

        ImageView iv3 = new ImageView(this.getActivity());
        //		iv3.setImageResource(R.drawable.pic3);
        iv3.setBackgroundResource(R.drawable.pic3);

        ImageView iv4 = new ImageView(this.getActivity());
        //		iv4.setImageResource(R.drawable.pic4);
        iv4.setBackgroundResource(R.drawable.pic4);

        imgs.add(iv1);
        imgs.add(iv2);
        imgs.add(iv3);
        imgs.add(iv4);

    }
    private void changePoint(int position) {
        // TODO Auto-generated method stub
        //将所有小点图标设置成灰色的图片
        for(ImageView iv:points){
            iv.setImageResource(R.drawable.page_control_off);
        }
        tv_main_super_title.setText(titles[position]);
        points.get(position).setImageResource(R.drawable.page_control_on);
    }
    class MyPagerAdapter extends PagerAdapter {

        //返回viewPager中视图的数量
        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return imgs.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            // TODO Auto-generated method stub
            return view == object;
        }

        //在viewPager缓存中增加对应的视图对象
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            // TODO Auto-generated method stub
            ImageView iv = imgs.get(position);
            container.addView(iv);
            return iv;
        }

        //在viewPager缓存中删除对应的视图对象
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            ImageView iv = imgs.get(position);
            container.removeView(iv);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            // TODO Auto-generated method stub
            return titles[position];
        }

    }
}
